package com.goodedeeds.webapp;

import com.youtills.core.auth.AuthDaoFactory;
import com.youtills.core.auth.IAuth;
import com.youtills.core.auth.IAuthenticationDao;
import com.youtills.core.email.EmailMessage;
import com.youtills.core.lang.StringUtil;
import com.youtills.core.web.HttpUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.MessageFormat;

/**
 * Created by IntelliJ IDEA.
 * User: rchiluve
 * Date: 1/28/14
 * Time: 8:59 PM
 * To change this template use File | Settings | File Templates.
 */
public class LoginHandler {

    public static final String AUTH_KEY = "quiggle.auth";

    private static final LoginHandler instance = new LoginHandler();

    private final IAuthenticationDao authenticationDao;

//    private final ConfigItem VERIFY_ACCOUNT_EMAIL_FROM = new ConfigItem("quiggle.verify.account.email.from");
//    private final ConfigItem VERIFY_ACCOUNT_EMAIL_SUBJECT = new ConfigItem("quiggle.verify.account.email.subject");
//    private final ConfigItem VERIFY_ACCOUNT_EMAIL_BODY = new ConfigItem("quiggle.verify.account.email.body");
//    private final ConfigItem QUIGGLE_SERVER_NAME = new ConfigItem("quiggle.server.name");
//    private final ConfigItem QUIGGLE_CONTEXT_NAME = new ConfigItem("quiggle.context.name", "/quiggle");


    private LoginHandler() {
        authenticationDao = AuthDaoFactory.getAuthenticationDao();
    }

    public static LoginHandler getInstance() {
        return instance;
    }

    public boolean doLogin(String login, String password, HttpServletRequest req, HttpServletResponse res){

        IAuth auth = authenticationDao.authenticateUser(login, password);
        if(auth != null){
            return doLogin(auth, req, res);
        }
        return false;
    }

    public boolean doLogin(IAuth auth, HttpServletRequest req, HttpServletResponse res){

        HttpSession session = req.getSession(true);
        session.setAttribute(AUTH_KEY, auth);

        String cookieKey = auth.getAuthId()  + "=" + auth.getAuthKey();

        HttpUtil.setCookie(res, AUTH_KEY, cookieKey, 600000);

        return true;
    }

    public void doLogout(HttpServletRequest req, HttpServletResponse res){

        HttpSession session = req.getSession();
        session.invalidate();
        Cookie cookie = new Cookie(AUTH_KEY, String.valueOf(-1));
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        res.addCookie(cookie);

    }

    public boolean validateAuth(IAuth auth){
        return auth != null && authenticationDao.validateAndExtendAuth(auth);
    }

    public IAuth fetchAuth(HttpServletRequest req, HttpServletResponse res){

        IAuth auth = fetchAuthFromHttpSession(req.getSession());
        if(validateAuth(auth)){
            return auth;
        }

        auth = fetchAuthFromCookie(req);
        if(validateAuth(auth)){
            return auth;
        }

        return null;
    }

    public static IAuth fetchAuthFromCookie(HttpServletRequest req){

        String cookieValue = HttpUtil.getCookieValue(req, AUTH_KEY);

        if(cookieValue != null){
            String[] auth = cookieValue.split("=");
            if(auth.length == 2){
                int authId = StringUtil.getNumber(auth[0], 0).intValue();
                String authKey = auth[1];
                if(authId > 0 && !StringUtil.isEmpty(auth[1])){
                    return AuthDaoFactory.getAuthenticationDao().getAuth(authId, authKey);
                }
            }
        }
        return null;
    }
    public IAuth fetchAuthFromHttpSession(HttpSession session){

        if(session != null){
            Object auth = session.getAttribute(AUTH_KEY);
            if(auth != null && auth instanceof IAuth){
                return (IAuth)auth;
            }
        }
        return null;
    }


    public void sendLockedEmail(String email, String unlockCode){
    	try{
	        EmailMessage emailMessage = new EmailMessage(email);
//	        emailMessage.setFrom(VERIFY_ACCOUNT_EMAIL_FROM.getString());
//	        emailMessage.setSubject(VERIFY_ACCOUNT_EMAIL_SUBJECT.getString());
	        emailMessage.setHtml(true);
//	        String body = MessageFormat.format(VERIFY_ACCOUNT_EMAIL_BODY.getString(), QUIGGLE_SERVER_NAME.getString(), QUIGGLE_CONTEXT_NAME.getString(), email, unlockCode);
//	        emailMessage.setBody(body);
//	        EmailSender.send(emailMessage);
    	}catch (Exception e) {
    		e.printStackTrace();
    	}
    }

}
